/**
 * 重置输入的id所代表的窗口的信息
 * @param form 要重置的窗口id
 */
function reset(formId) {
    document.getElementById(formId).reset();
}

function getStrLength(str) {
    return str.replace(/[^\x00-\xff]/g, 'xx').length;
}

function isLogout() {
    var result = confirm("确认退出？不在多看一会儿吗？")
    return result;
}

function enterSearchIcon(id, type) {
    var obj = document.getElementById(id);
    if (type == "enter")
        obj.style.color = "rgb(51,143,255)";
    else
        obj.style.color = "rgb(0,0,0)";
}

/**
 *搜索文章
 * @param obj
 */
function searchArticle(keyCode) {
    var obj = document.getElementById("search");
    var key = obj.value;
    if (key == null || key.length <= 0)
        return;
    if (keyCode == 13) {
        var url = window.location.href;
        if (url.search("/in/home")) {
            url = url.substring(0, url.indexOf("in/home"));
        }
        url = url.endWith("#") ? url.substring(0, url.length - 1) : url;
        window.location.href = url + "article/searchShare?key=" + key;
    }
}

function image_click() {
    document.getElementById('loadPic').click()
}

function headImage_click() {
    document.getElementById('loadHead').click()
}

function submitHead_click() {
    document.getElementById('submitHead').click();
}

function edit_click() {
    document.getElementById("edit").click();
}

/**
 * body加载时改变左边导航栏得背景颜色
 * @param leftNav
 */
function changeLeftNavColor(leftNav) {
    document.getElementById("li" + leftNav).style.backgroundColor = "paleturquoise"
}

/**
 * 判断分享的内容是否符合要求（不为空且不包含关键字）
 * @returns {boolean}
 */
function inputInvailds(userId) {
    var result = true;
    var shareBox = document.getElementById("shareContent");
    if (shareBox.value.length <= 0) {
        shareBox.focus();
        return false;
    }
    var pic = document.getElementById("loadPic");
    if (pic.files.length < 1 || pic.files.length > 6) {
        alert("发布分享时至少要有一张图片");
        return false;
    }
    var url = window.location.href.substring(0, window.location.href.indexOf("/home/")) + "/out";
    $.ajax({
        type: "post",
        dataType: "json",
        url: "/article/share/check",
        async: false,
        data: {
            content: shareBox.value,
            isShare: true,
            userId: userId
        },
        cache: false,
        success: function (map) {
            if (!map["isLogin"]) {
                window.location.href = url;
                result = false;
            } else if (!map["isLegal"]) {
                alert("您的分享文字里包含了一些非文明用语，请检查用语后再点击发布。");
                shareBox.focus();
                result = false;
            } else if (!map["isAllowShare"]) {
                alert("您被管理员限制发布分享，请联系管理员恢复发布分享功能！");
                result = false;
            } else {
                result = true;
            }
        },
        error: function () {
            alert("出现异常，请刷新网页!");
            result = false;
        }
    });
    return result;
}

/**
 * 显示评论框
 * @param obj 评论标签的引用
 */
function showComment(obj) {
    var comment = obj.parentNode.nextElementSibling || obj.parentNode.nextSibling;
    if (comment.style.display == "none")
        comment.style.display = "block";
    else
        comment.style.display = "none";
}

function showCommentDelete(outIndex, inIndex, type) {
    if (type == "show")
        document.getElementById("deleteComment" + outIndex + inIndex).style.display = "inline-block";
    else
        document.getElementById("deleteComment" + outIndex + inIndex).style.display = "none";
}

function deleteComment(thisObj, commentId) {
    if (!confirm("确认删除评论？"))
        return false;
    var url = window.location.href;
    $.ajax({
        type: "post",
        url: "/article/deleteComment",
        dataType: "json",
        data: {
            commentId: commentId
        },
        cache: false,
        success: function (result) {
            if (!result["isLogin"]) {
                if (url.search("article/share_detail")) {
                    url = url.substring(0, url.indexOf("article/share_detail"));
                } else {
                    url = url.substring(0, url.indexOf("in/home"));
                }
                window.location.href = url + "in/out";
            } else if (result["isSuccess"]) {
                thisObj = thisObj.parentNode;
                thisObj.style.display = "none";
                thisObj = thisObj.previousElementSibling || thisObj.previousSibling;
                thisObj.style.display = "none";
                var obj = thisObj.parentNode.parentNode;
                obj = obj.previousElementSibling || thisObj.previousSibling;
                obj = obj.children[2];
                var count = parseInt(obj.innerHTML.substring(obj.innerHTML.lastIndexOf("(") + 1, obj.innerHTML.lastIndexOf(")")));
                count = (count - 1 >= 0 ? count - 1 : 0);
                obj.innerHTML = obj.innerHTML.substring(0, obj.innerHTML.lastIndexOf("(") + 1) + count + ")";

            } else {
                alert("出现异常，请刷新网页重新尝试")
            }
        },
        error: function () {
            alert("出现异常，请刷新网页重新尝试");
        }
    });
}

/**
 * 评论分享并动态显示在页面
 * @param obj
 */
function commentShare(obj, userId, articleId, outInex) {
    obj = obj.previousElementSibling || obj.previousSibling;
    var content = obj.value;
    if (content.length <= 0 || content.length > 100) {
        obj.focus();
        return false;
    }
    var result = true;
    var oldUrl = window.location.href;
    $.ajax({
        type: "post",
        dataType: "json",
        url: "/article/checkContent",
        data: {
            content: content
        },
        cache: false,
        async: false,
        success: function (map) {
            if (!map["isLogin"]) {
                if (oldUrl.search("article/share_detail")) {
                    oldUrl = oldUrl.substring(0, oldUrl.indexOf("article/share_detail"));
                } else {
                    oldUrl = oldUrl.substring(0, oldUrl.indexOf("in/home"));
                }
                window.location.href = oldUrl + "in/out";
                result = false;
            } else if (!map["isLegal"]) {
                alert("您的评论里包含了一些非文明用语，请检查用语后再点击评论。");
                obj.focus();
                result = false;
            } else {
                result = true;
            }
        },
        error: function () {
            alert("出现异常，请刷新页面");
        }
    });
    if (!result)
        return false;
    obj.value = "";
    $.ajax({
        type: "post",
        dataType: "json",
        url: "/article/comment",
        data: {
            content: content,
            userId: userId,
            articleId: articleId
        },
        success: function (result) {
            if (result["isSuccess"] == false)
                alert("出现异常");
            else {
                obj = obj.previousElementSibling || obj.previousSibling;
                var src = obj.src;
                obj = obj.previousElementSibling || obj.previousSibling;
                var name = obj.value;
                //评论列表div
                obj = obj.parentNode.nextElementSibling || obj.parentNode.nextSibling;
                var html = obj.innerHTML;
                var inIndex = obj.children.length;
                obj.innerHTML = "<hr style='margin: 2px 0px 2px'/>" +
                    "<div style='display: block' onmouseover=\"showCommentDelete(\'" + outInex + "\',\'" + inIndex + "\',\'show\')\" onmouseout=\"showCommentDelete(\'" + outInex + "\',\'" + inIndex + "\',\'close\')\">" +
                    "<img src='" + src + "' width='30px' height='30px' style='margin: 5px 5px 2px 15px;display: inline'/>" +
                    "<p style='color: red;font-size: 10px;display: inline'>" + name + "： </p>" +
                    "<p style='display: inline'>" + content + "</p>" +
                    "<small style='display: block;margin-left: 52px'>" + curentTime() + "</small>" +
                    " <a id='deleteComment" + outInex + inIndex + "' " +
                    "style='cursor:pointer;display: none;float:right;margin-top: -25px;margin-right: 35px;font-style: italic;' " +
                    "onclick=\"deleteComment(this,\'" + result["commentId"] + "\')\">删除</a>" +
                    "</div>" + html;
                //修改评论右边的数目使其+1
                //分享下面的处理操作div
                obj = obj.parentNode.previousElementSibling || obj.parentNode.previousSibling;
                obj = obj.children[2];
                var commentCount = parseInt(obj.innerHTML.substring(obj.innerHTML.lastIndexOf('(') + 1, obj.innerHTML.length - 1)) + 1;
                obj.innerHTML = "<span class='glyphicon glyphicon-comment' style='color:rgb(46,100,148)'></span> 评论(" + commentCount + ")";
            }
        },
        error: function () {
            alert("ajax出现异常");
        }
    });
}

function changeAuthority(obj) {
    document.getElementById("authority").value = obj.options[obj.selectedIndex].value;
}

/**
 * 显示图片
 * @param file
 * @returns {boolean}
 */
function viewImage(file) {
    var imgCount = document.getElementById("imgCount");
    var preview = document.getElementsByName("preview");
    var localImagId = document.getElementById("sharePicGroup");
    localImagId.style.display = "block";
    //通过二进制数表示其输入了几张图片,111111，表示输入6张
    imgCount.value = Math.pow(2, file.files.length) - 1;
    for (var i = 0; i < file.files.length >= 6 ? 6 : file.files.length; i++) {
        if (file.files && file.files[i]) {
            //火狐下
            preview[i].style.display = "inline";
            preview[i].style.width = "200px";
            preview[i].style.height = "120px";
            preview[i].src = window.URL.createObjectURL(file.files[i]);
        } else {
            //ie下，使用滤镜
            file.select();
            var imgSrc = document.selection.createRange().text;

            var localImagId = document.getElementById("sharePicGroup");
            try {
                localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                locem("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
            } catch (e) {
                //alert("您上传的图片格式不正确，请重新选择!");
                return false;
            }
            document.selection.empty();
        }
    }
    for (var i = file.files.length; i <= 6; i++) {
        preview[i].style.display = "none";
    }
    return true;
}

/**
 * 双击图片删除图片
 * @param image 图片控件
 */
function picDbClick(image) {
    var loadPic = document.getElementById("loadPic");
    var imgCount = document.getElementById("imgCount");
    var preview = document.getElementsByName("preview");
    for (var i = 0; i < preview.length; i++) {
        if (preview[i].id === image.id) {
            var count = parseInt(imgCount.value) - Math.pow(2, i);
            imgCount.value = count + "";
            break;
        }
    }
    image.style.display = "none";
}

/**
 * 点击点赞或收藏后改变标签颜色
 * @param obj
 * @param type
 * @returns {boolean}
 */
function changeColor(obj, type) {
    var span = obj.children[0];
    if (span.style.color === "rgb(46, 100, 148)") {
        if (type === "collect")
            obj.innerHTML = "<span class='glyphicon glyphicon-star' id='collect'  style='color: rgb(255,0,0)'>已收藏";
        else {
            var num = parseInt(obj.innerText) + 1;
            obj.innerHTML = "<span class='glyphicon glyphicon-thumbs-up' id='good' style='color: rgb(255,0,0)'>" + num;
        }
    } else {
        if (type === "collect") {
            if (confirm("确定取消收藏？"))
                obj.innerHTML = "<span class='glyphicon glyphicon-star-empty' id='collect' style='color:rgb(46,100,148'>收藏";
            else
                return false;
        } else {
            var num = parseInt(obj.innerText) - 1;
            obj.innerHTML = "<span class='glyphicon glyphicon-thumbs-up' id='good' style='color:rgb(46,100,148'>" + num;
        }
    }
    return true;
}

/**
 * （取消）点赞或（取消）收藏成功后更新页面
 * @param obj
 * @param html
 */
function update(obj, html) {
    //得到分享内容整个的div
    obj = obj.parentNode.parentNode;
    obj.style.display = "none";
    obj = obj.parentNode;
    var i = 0;
    for (; i < obj.children.length; i++) {
        if (obj.children[i].style.display != "none") {
            break;
        }
    }
    if (i == obj.children.length) {
        obj.innerHTML = html;
    }
}

/**
 * 点赞
 * @param obj
 */
function praise(obj, leftNav) {
    changeColor(obj, "good");
    var span = obj.children[0];
    var hidden = obj.nextElementSibling || obj.nextSibling;
    var data = hidden.value.split('@');
    var userId = data[0];
    var articleId = data[1];
    var isLike = data[2];
    if (span.style.color === "rgb(46, 100, 148)")
        isLike = "F";
    else
        isLike = "T";
    var url = "/article/praise?userId=" + userId + "&articleId=" + articleId + "&isLike=" + isLike;
    var oldUrl = window.location.href;
    $.ajax({
        type: "post",
        dataType: "json",
        url: url,
        data: null,
        processData: false,
        contentType: false,
        success: function (result) {
            if (!result["isLogin"]) {
                if (oldUrl.search("article/share_detail")) {
                    oldUrl = oldUrl.substring(0, oldUrl.indexOf("article/share_detail"));
                } else {
                    oldUrl = oldUrl.substring(0, oldUrl.indexOf("in/home"));
                }
                window.location.href = oldUrl + "in/out";
                return;
            }
            if (!result["isSuccess"]) {
                alert("error");
                return;
            }
            if (leftNav == undefined) {//在article_share里点赞
                var pobj = document.getElementById("likeListP");
                var userName = document.getElementById("userName").innerText;
                var num = obj.innerText;
                var prefix = pobj.innerHTML.substring(0, pobj.innerHTML.lastIndexOf((isLike == "T" ? parseInt(num) - 1 : parseInt(num) + 1) + "人"));
                var suffix = "人点赞过";
                if (isLike == "T") {
                    if (num==1)
                        pobj.innerHTML = "<em>" + userName + "</em>&nbsp;共1人点赞过";
                    else
                        pobj.innerHTML = "<em>" + userName + "</em>、" + prefix + num + suffix;
                } else {
                    if(num==0)
                        pobj.innerText = "暂时无人点赞";
                    else{
                        prefix = prefix.substring(prefix.indexOf("、") + 1);
                        pobj.innerHTML = prefix + num + suffix;
                    }
                }
            } else if (leftNav == 3) {
                var html = "<div class='share home_center_block' " +
                    "style='margin-top: 14px;margin-bottom: 10px; opacity: 100%;height: 150px'>" +
                    "<h3 style='text-align:center;margin-top: 10px;padding-top: 15px;'><em>没有点赞过任何文章！<br/>" +
                    "可以<a href='/in/home?leftNav=1'>前往主页</a>为自己喜欢或感兴趣的文章点个赞，点过赞的都会出现在这里哦</em></h3>" +
                    "</div>";
                update(obj, html);
            }
        },
        error: function () {
            alert("ajax出现异常");
        }
    });
}

/**
 * 收藏
 * @param obj
 * @returns {boolean}
 */
function collect(obj, leftNav) {
    if (!changeColor(obj, "collect"))
        return false;
    var span = obj.children[0];
    var hidden = obj.nextElementSibling || obj.nextSibling;
    var data = hidden.value.split('@');
    var userId = data[0];
    var articleId = data[1];
    var isCollect = data[2];
    if (span.style.color === "rgb(46, 100, 148)")
        isCollect = "F";
    else
        isCollect = "T";

    var url = "/article/collect?userId=" + userId + "&articleId=" + articleId + "&isCollect=" + isCollect;
    var oldUrl = window.location.href;
    $.ajax({
        type: "post",
        dataType: "json",
        url: url,
        data: null,
        processData: false,
        contentType: false,
        success: function (result) {
            if (!result["isLogin"]) {
                if (oldUrl.search("article/share_detail")) {
                    oldUrl = oldUrl.substring(0, oldUrl.indexOf("article/share_detail"));
                } else {
                    oldUrl = oldUrl.substring(0, oldUrl.indexOf("in/home"));
                }
                window.location.href = oldUrl + "in/out";
                return false;
            }
            if (!result["isSuccess"]) {
                alert("出现异常");
                return false;
            }
            if (leftNav == 2) {
                var html = "<div class='share home_center_block' " +
                    "style='margin-top: 14px;margin-bottom: 10px; opacity: 100%;height: 150px'>" +
                    "<h3 style='text-align:center;margin-top: 10px;padding-top: 15px;'><em>没有收藏任何文章！<br/>" +
                    "可以<a href='/in/home?leftNav=1'>前往主页</a>点击收藏自己喜欢或感兴趣的文章，就会出现在这里哦</em></h3>" +
                    "</div>";
                update(obj, html);
            }
        },
        error: function () {
            alert("出现异常,请刷新网页重新操作");
        }
    })
}

/**
 * 显示点赞列表
 * @param obj
 */
function showLiker(obj) {
    var shareliker = document.getElementsByClassName("share_Liker")[0];
    if (shareliker.style.display == "none") {
        obj.innerHTML = "<span class='glyphicon glyphicon-chevron-up'></span>";
        shareliker.style.display = "block";
    } else {
        obj.innerHTML = "<span class='glyphicon glyphicon-chevron-down'></span>";
        shareliker.style.display = "none";
    }
}

/**
 * 删除自己发布的分享
 * @param articleId
 * @param obj
 * @returns {boolean}
 */
function deleteShare(articleId, obj) {
    if (!confirm("确认删除该分享？"))
        return false;
    var url = window.location.href.substring(0, window.location.href.indexOf("/home/")) + "/out";
    $.ajax({
        type: "post",
        dataType: "json",
        url: "/article/deleteShare",
        data: {
            articleId: articleId
        },
        cache: false,
        success: function (result) {
            if (!result["isLogin"]) {
                window.location.href = url;
            } else if (result["isSuccess"]) {
                obj = obj.parentNode.parentNode.parentNode.parentNode;
                obj.style.display = "none";
                obj = obj.parentNode;
                for (var i = 0; i < obj.children.length; i++) {
                    if (obj.children[i].style.display != "none") {
                        break;
                    }
                    if (i == obj.children.length) {
                        var html = "<div class='share' style='margin-top: 2%;opacity: 100%'>" +
                            "<h3 style='padding-top: 10px'>当前暂无分享，快分享你自己的精彩瞬间吧！</h3>" +
                            "</div>";
                        obj.innerHTML = html;
                    }
                }
            } else {
                alert("error");
            }
        },
        error: function () {
            alert("出现异常,请刷新网页重新操作");
        }
    })
}

/**
 * 修改文章的权限
 * @param articleId
 * @param authority
 */
function updateAuthority(articleId, authority) {
    var msg = (authority == 1 ? "确认将该分享设为仅自己可见？" : "确认将该分享设为所有人可见？");
    if (!confirm(msg))
        return false;
    var obj = document.getElementById("name_and_authority_" + articleId);
    var html = obj.innerHTML;
    if ((html.search("<") > 0 && authority == 1) || (html.search("<") < 0 && authority == 0))
        return false;

    var url = window.location.href.substring(0, window.location.href.indexOf("/home/")) + "/out";
    $.ajax({
        type: "post",
        dataType: "json",
        url: "/article/updateAuthority",
        data: {
            articleId: articleId,
            authority: authority
        },
        cache: false,
        success: function (result) {
            if (!result["isLogin"]) {
                window.location.href = url;
            } else if (result["isSuccess"]) {
                if (authority == 1) {
                    html += "<span class='glyphicon glyphicon-lock' style='color: red;'></span>"
                } else {
                    html = html.substring(0, obj.innerHTML.indexOf('<'));
                }
                obj.innerHTML = html;
                showTips("修改成功", 100, 2);
            } else {
                alert("error");
            }
        },
        error: function () {
            alert("出现异常,请刷新网页重新操作");
        }
    })
}

/**
 * 屏蔽分享
 * @param articleId
 * @param userId
 * @param shareId
 * @returns {boolean}
 */
function shieldShare(articleId, userId, shareId) {
    if (!confirm("确认屏蔽该分享？\n注：一旦确认，就无法撤销,在首页里将屏蔽该分享"))
        return false;
    var url = window.location.href.substring(0, window.location.href.indexOf("/home/")) + "/out";
    $.ajax({
        type: "post",
        url: "/article/shield",
        dataType: "json",
        data: {
            articleId: articleId,
            userId: userId
        },
        cache: false,
        success: function (result) {
            if (!result["isLogin"]) {
                window.location.href = url;
            } else if (result["isSuccess"]) {
                document.getElementById(shareId).style.display = "none";
            } else {
                alert("error，请重新刷新页面");
            }
        },
        error: function () {
            alert("出现异常，请重新刷新页面");
        }
    })
}


/**
 * 点击文章进入文章内部查看细节
 */
function turnInArticle(articleId) {
    var url = window.location.href
    if (url.search("/in/home")) {
        url = url.substring(0, url.indexOf("in/home"));
    }
    url = (url.endWith("#") ? url.substring(0, url.length - 1) : url);
    url = url + "article/share_detail?aId=" + articleId;
    var nopen = window.open(url);
    nopen.focus();
}

/**
 * 编辑个人主页
 * @param obj
 */
function editPersonMes(obj) {
    if (obj.innerText == "编辑") {
        document.getElementById("primaryView").style.display = "none";
        document.getElementById("editView").style.display = "block";
        obj.innerText = "保存"

    } else {
        var nickname = document.getElementById("nickname").value;
        if (getStrLength(nickname) < 1 || getStrLength(nickname) > 18) {
            document.getElementById("nickname").focus();
        }
        document.getElementById("primaryView").style.display = "block";
        document.getElementById("editView").style.display = "none";
        obj.innerText = "编辑";
        var userId = document.getElementById("userId").value;
        var obj = document.getElementById("province");
        var address = obj.options[obj.selectedIndex].text;
        var sex = (document.getElementById("man_radio").checked ? "男" : "女");
        var birthday = document.getElementById("birthday").value;
        var introduction = document.getElementById("introduction").value;
        var url = window.location.href.substring(0, window.location.href.indexOf("/home/")) + "/out";
        $.ajax({
            type: "post",
            dataType: "json",
            url: "/article/updateUserMsg",
            data: {
                userId: userId,
                nickname: nickname,
                address: address,
                sex: sex,
                birthday: birthday,
                introduction: introduction
            },
            cache: false,
            success: function (result) {
                if (!result["isLogin"]) {
                    window.location.href = url;
                } else if (result["isSuccess"]) {
                    document.getElementById("viewNickName").innerText = nickname;
                    document.getElementById("viewAddress").innerText = address;
                    document.getElementById("viewSex").innerText = sex;
                    var pobj = document.getElementById("nameOfUnderHeadPic");
                    pobj.innerText = nickname;
                    var len = nickname.replace(/[\u0391-\uFFE5]/g, "xx").length;
                    pobj.style.marginLeft = (len <= 10 ? 75 : 75 - (len - 10) / 2) + "%";
                    pobj.style.width = (len <= 10 ? 150 : (150 + (len - 10) * 25 / 2)) + "px";
                    if (birthday.length > 0)
                        document.getElementById("viewBirthday").innerText = birthday;
                    else {
                        var html = "<a style='cursor: pointer;' onclick='edit_click()'>立即填写</a> 选择自己的生日";
                        document.getElementById("viewBirthday").innerHTML = html;
                    }
                    if (introduction.length > 0)
                        document.getElementById("viewIntroduction").innerText = introduction;
                } else {
                    alert("error");
                }
            },
            error: function () {
                alert("出现异常,请刷新网页重新操作");
            }
        })
    }

}

function updatePassword() {
    var oldPsw = document.getElementById("oldPsw").value;
    var newPsw1 = document.getElementById("newPsw1").value;
    var newPsw2 = document.getElementById("newPsw2").value;
    if (oldPsw.length <= 0) {
        alert("请输入原密码！");
        document.getElementById("oldPsw").focus();
        return false;
    }
    if (newPsw1.length <= 0) {
        alert("请输入新的密码");
        document.getElementById("newPsw1").focus();
        return false;
    }
    if (newPsw2.length <= 0) {
        alert("请再次输入密码");
        document.getElementById("newPsw2").focus();
        return false;
    }
    if (newPsw1 != newPsw2) {
        alert("两次输入的密码不相同，请检查后重新输入");
        return false;
    }
    if (oldPsw == newPsw1) {
        alert("新密码不能原来的密码一样");
        return false;
    }
    //密码验证
    var regex = /^[a-z0-9]{6,20}$/;
    if (!regex.test(newPsw1)) {
        window.alert("提示\n\n密码必须为6到20位之间的字符，只能包含数字和字母");
        document.getElementById("newPsw1").focus();
        return false;
    }
    var url = window.location.href.substring(0, window.location.href.indexOf("/home/")) + "/out";
    $.ajax({
        type: "post",
        url: "/article/updatePsw",
        dataType: "json",
        data: {
            oldPsw: oldPsw,
            newPassword: newPsw1
        },
        cache: false,
        success: function (result) {
            if (!result["isLogin"]) {
                window.location.href = url;
            } else if (!result["isPswOK"]) {
                alert("输入的原密码错误");
                document.getElementById("oldPsw").focus();
            } else if (result["isSuccess"]) {
                alert("修改成功");
                document.getElementById("close").click();
            } else {
                alert("出现异常，请刷新网页重新操作");
            }
        },
        error: function () {
            alert("出现异常，请刷新网页重新操作");
        }
    });
}

/**
 * 判断string是否以指定字符串结尾
 * @param endStr 指定字符串
 * @returns {boolean}
 */
String.prototype.endWith = function (endStr) {
    var d = this.length - endStr.length;
    return (d >= 0 && this.lastIndexOf(endStr) == d)
};

/**
 * 得到当前时间
 * @returns {string}
 */
function curentTime() {
    var now = new Date();

    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日

    var hh = now.getHours();            //时
    var mm = now.getMinutes();          //分
    var ss = now.getSeconds();            //秒

    var clock = year + "-";

    if (month < 10)
        clock += "0";

    clock += month + "-";

    if (day < 10)
        clock += "0";

    clock += day + " ";

    if (hh < 10)
        clock += "0";

    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm + ":";
    if (ss < 10) clock += '0';
    clock += ss;
    return (clock);
}


/**
 * 得到一个可以自己消失的弹窗
 * @param content 要显示的内容
 * @param height 离窗口顶部的距离
 * @param time 多少秒后关闭的时间，单位为秒
 */
function showTips(content, height, time) {
    //窗口的宽度
    var windowWidth = $(window).width();
    var tipsDiv = '<div class="tipsClass">' + content + '</div>';
    $('body').append(tipsDiv);
    $('div.tipsClass').css({
        'top': height + 'px',
        'left': (windowWidth / 2) - 350 / 2 + 'px',
        //'position'  : 'absolute',
        'padding': '10px 5px',
        'background': '#8FBC8F',
        'font-size': 25 + 'px',
        'margin': '0 auto',
        'text-align': 'center',
        'width': '100px',
        'height': '100px',
        'color': '#fff',
        'opacity': '0.8',
        'z-index': '999px'
    }).show();
    setTimeout(function () {
        $('div.tipsClass').fadeOut();
    }, (time * 1000));
}

/****************以下为管理员操作的函数**********************/
/**
 * 修改用户的分享权限
 * @param userId
 * @param obj
 * @returns {boolean}
 */
function reverseAllowShare(userId, obj) {
    if (!confirm("确定" + obj.innerText + "用户【" + userId + "】发布分享？")) {
        return false;
    }
    var isAllowShare = (obj.innerText === "允许" ? "T" : "F");
    var url = window.location.href.substring(0, window.location.href.indexOf("/home/")) + "/out";
    $.ajax({
        type: "post",
        url: "/article/updateAllowShare",
        dataType: "json",
        data: {
            userId: userId,
            isAllowShare: isAllowShare
        },
        success: function (result) {
            if (!result["isLogin"]) {
                window.location.href = url;
            } else if (result["isSuccess"]) {
                var primaryStatu = obj.innerText;
                var curStatu = (obj.innerText == "允许" ? "禁止" : "允许");
                obj.innerText = curStatu;
                obj = obj.parentNode;
                obj.innerHTML = primaryStatu + obj.innerHTML.substring(obj.innerHTML.indexOf('<'));
            } else {
                alert("修改失败，请刷新网页再重新尝试");
            }
        },
        error: function () {
            alert("出现异常，请刷新网页再重新操作");
        }
    });
}

/**
 * 修改关键字
 * @param obj
 */
function editKeyword(obj) {
    var keyword = obj.children[1].innerText;
    var newKeyword = prompt("修改关键词", keyword);
    if (newKeyword == null || keyword == newKeyword)
        return;
    else if (newKeyword == "") {
        alert("关键词不能为空");
        return;
    }
    var url = window.location.href.substring(0, window.location.href.indexOf("/home/")) + "/out";
    $.ajax({
        type: "post",
        dataType: "json",
        url: "/article/updateKeyword",
        data: {
            keyword: keyword,
            newKeyword: newKeyword
        },
        //cache:false,
        success: function (result) {
            if (!result["isLogin"]) {
                window.location.href = url;
            } else if (result["isSuccess"]) {
                obj.children[1].innerHTML = newKeyword +
                    "<span class='badge' style='float:right;'>" +
                    "   <span class='glyphicon glyphicon-remove'></span>" +
                    "</span>";
            } else {
                alert("修改失败，关键词\"" + newKeyword + "\"已存在");
            }
        },
        error: function () {
            alert("出现异常，请刷新页面重新操作");
        }
    });
}

/**
 * 删除关键字
 * @param obj
 * @returns {boolean}
 */
function deleteKeyword(obj) {
    event.stopPropagation();//禁止触发父元素的事件
    if (!confirm("确认删除该关键字？"))
        return false;
    var keyword = obj.parentNode.innerText;
    var url = window.location.href.substring(0, window.location.href.indexOf("/home/")) + "/out";
    $.ajax({
        type: "post",
        dataType: "json",
        url: "/article/deleteKeyword",
        data: {
            keyword: keyword
        },
        success: function (result) {
            if (!result["isLogin"]) {
                window.location.href = url;
            } else if (result["isSuccess"]) {
                obj = obj.parentNode.parentNode;
                pobj = obj.parentNode;
                var index = parseInt(obj.children[0].innerText);
                //去掉要删除的面板
                pobj.removeChild(obj);
                //修改序号
                for (var i = index; i < pobj.children.length + 1; i++) {
                    var id = "index" + (i + 1);
                    var tdobj = document.getElementById(id);
                    tdobj.innerText = parseInt(tdobj.innerText) - 1;
                    tdobj.id = "index" + i;
                }
            } else {
                alert("删除失败");
            }
        },
        error: function () {
            alert("出现异常，请重新刷新页面");
        }
    });
}

/**
 * 添加关键字
 * @param obj
 */
function addKeyword(obj) {
    var keyword = document.getElementById("newKeyword").value;
    if (keyword == null || keyword.length == 0) {
        alert("关键词不能为空");
        obj.focus();
        return;
    }
    var url = window.location.href.substring(0, window.location.href.indexOf("/home/")) + "/out";
    $.ajax({
        type: "post",
        dataType: "json",
        url: "/article/addKeyword",
        data: {
            keyword: keyword
        },
        cache: false,
        success: function (result) {
            if (!result["isLogin"]) {
                window.location.href = url;
            } else if (result["isSuccess"]) {
                document.getElementById("newKeyword").value = "";
                obj = document.getElementById("keywordTable");
                //修改序号和id
                for (var i = obj.children.length; i > 0; i--) {
                    var id = "index" + i;
                    var tdobj = document.getElementById(id);
                    tdobj.innerText = parseInt(tdobj.innerText) + 1;
                    tdobj.id = "index" + (i + 1);
                }
                //添加新的关键字行
                obj.innerHTML =
                    "<tr onclick='editKeyword(this)'>" +
                    "   <td id='index1' width='50px'>1</td>" +
                    "   <td>" + keyword +
                    "       <span class='badge' style='float:right;' onclick='deleteKeyword(this)'>" +
                    "           <span class='glyphicon glyphicon-remove'></span>" +
                    "       </span>" +
                    "   </td>" +
                    "</tr>" +
                    obj.innerHTML;
                obj = obj.parentNode.parentNode;
                var height = parseInt(obj.style.height.substring(0, obj.style.height.lastIndexOf("px")));
                obj.style.height = 39 + height + "px";
            } else {
                alert("关键词”" + keyword + "“已存在");
            }
        },
        error: function () {
            alert("出现异常，请刷新网页重新操作");
        }
    });

}
